<!--
  - Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  - Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
  - Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
  - Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
  - Vestibulum commodo. Ut rhoncus gravida arcu.
  -->

<style>
  @import "../../../static/z39pc/css/app.6689eaa302.css";
  @import "../../../static/z39pc/css/app.bb9deb9e54.css";
  @import "../../../static/z39pc/css/animate.min.css";
  @import "../../../static/z39pc/css/mycss/taskDetail.css";
  @import "../../../static/z39pc/css/mycss/task.css";
</style>
<template>

  <div class="task-main-container">
    <div id="mainBody" class="chrome webkit win modal-open" style="overflow-x: hidden;">
      <div id="nTalk_post_hiddenElement"
           style="left: -10px; top: -10px; visibility: hidden; display: none; width: 1px; height: 1px;"></div>

      <header-nav></header-nav>

      <div id="mainContent" style="background: none;">
        <!--<template>-->
        <div class="kanban-view">
          <div class="container-left-content active">
            <div class="show-box">
              <div class="icon-right el-icon-d-arrow-right">

              </div>
            </div>
            <div class="storageBox animated RSQ_fadeInLeft" id="storageBox">
              <header style="line-height: 64px;font-size: 14px;">
                <!--<template>
                                  <el-tabs v-model="boxTab" type="card">
                                      <el-tab-pane label="任务箱" name="box"></el-tab-pane>
                                      <el-tab-pane label="任务清单" name="taskList"></el-tab-pane>
                                  </el-tabs>
                              </template>-->
                任务箱（总数：{{nonesList.length}}）
                <div class="inboxDropDown dropDown" style="border:0">
                  <i class="dropdown-toggle el-icon-d-arrow-left hide-box" data-toggle="dropdown"
                     aria-expanded="false"></i>
                </div>

              </header>
              <div id="left-box-container1" v-show="boxTab=='box'">
                <div id="buttonDiv">
                  <div id="storageAddInputLi" style="display: block;border-bottom:1px solid #00529a"
                       @keyup.ctrl.enter="addTask" @dragenter="cleanEvent" @dragover="cleanEvent" @drop="dropHandle">

                    <!-- <input id="storageAddInput" class="type-caption-white" v-model="addTaskTitle" placeholder="任务标题"></input> -->

                    <textarea id="storageAddTextarea" name="" rows="3" cols="" v-model="addTaskTitle"
                              v-bind:placeholder="addTaskTitlePlaceholder" ref="outTextarea">

                  </textarea>
                  </div>

                  <el-button class="btn" type="primary" size="medium " :loading="addBtnLoading" @click="addTask">添加
                  </el-button>

                </div>
                <div id="storageUlDiv">
                  <ul class="ui-sortable unsort">
                    <draggable class="dragArea" :list="nonesList" tagKey="none" :options="{group:'task'}"
                               @remove="dragRemove" :move="dragMove" @add="dragAddNones">

                      <template v-for="(item,index) in nonesList">
                        <li class="kanban-Item-container task-11 animated tooltipstered" :taskId="item.id">

                          <div class="left">
                            <div class="checkboxContainer"><span class="diyCheckbox" style="cursor: pointer;"><i
                              class="icon-check_box_outline_blank blank"></i><i class="icon-check check"></i><div
                              class="checkTail"></div></span></div>
                          </div>
                          <div class="right">
                            <div class="portrait-container">
                              <!--<img class="portrait" src="../images/avatar.png" draggable="false">
                                                          <div class="time">07-11</div>-->
                            </div>
                            <div class="row1"><span v-bind:title="item.title+'\n'+item.desc" class="kanban-item-title">{{(index + 1) + '.' + item.title}}</span>
                              <!--<div class="receive-btn" style="display: none;">领取</div>-->
                            </div>
                            <div class="dateNode node"></div>
                          </div>
                        </li>
                      </template>

                    </draggable>
                  </ul>
                </div>
              </div>
              <div id="left-box-container2" v-show="boxTab=='Tasklist'">
                <ul class="ui-sortable unsort" style="height: 100%;">
                </ul>
              </div>
              <!--<div class="total-account">
                              总数：{{nonesList.length}}
                          </div>-->
            </div>

          </div>
          <div class="container-right">
            <div class="container-right-top-bg"></div>
            <div class="container-right-bottom-bg"></div>
            <div class="container-right-content">
              <div class="weatherAndSwitchView animated RSQ_fadeInRight">
                <div class="switch3Ul blue" style="left: 2rem;">
                  <ul class="task-tab" id='listTypeTab'>
                    <li class="task-tab-item active" @click="onChangeTime(0)">
                      <router-link to="/todayTask" tag="div">日</router-link>
                    </li>
                    <li class="task-tab-item" @click="onChangeTime(1)">
                      <router-link to="/weekTask" tag="div">周</router-link>
                    </li>
                    <li class="task-tab-item" @click="onChangeTime(2)">
                      <router-link to="/monthTask" tag="div">月</router-link>
                    </li>
                    <li class="task-tab-item" @click="onChangeTime(3)">
                      <router-link to="/yearTask" tag="div">年</router-link>
                    </li>
                    <li class="task-tab-item" @click="onChangeTime(4)">
                      <router-link to="/projectTask" tag="div">项目</router-link>
                    </li>
                  </ul>
                </div>
                <!--<div class="row" id='hl-switch'>
                                  <el-switch v-model="memberActive" on-color="#13ce66" on-text="" off-text="" @change="memberActiveChange()">
                                  </el-switch>
                              </div>-->

                <div class="type_filter switch3Ul project-swiper"
                     style="max-width: 30%;overflow: hidden;white-space: nowrap;">
                  <ul class="inUl prolist projectList  swiper-wrapper" style="width: 100000px;">
                    <li class="item swiper-slide" :class="projectId==''?'active':''" @click="projectCli('')">
                      无
                    </li>
                    <template v-for="(item,index) in projects">
                      <li class='item swiper-slide' :class="projectId==item.id?'active':''" :proId="item.id"
                          @click="projectCli(item.id)">
                        {{item.title}}
                      </li>
                    </template>

                  </ul>

                </div>
                <div class="project-btn-container">
                  <div class="add-container" @click="showProjectDialog('add')">
                    <div class="add-container-bg">
                      <span></span>添加项目
                    </div>
                  </div>
                  <div v-show="projectId!=''" class="delete-container" @click="deleteProject()">
                    <div class="delete-container-bg">
                      <span></span>
                    </div>
                  </div>
                  <div v-show="projectId!=''" class="set-container" @click="showProjectDialog('edit')">
                    <div class="set-container-bg">
                      <span></span>
                    </div>
                  </div>
                  <!--<div v-show="projectId!=''" class="member-switch">
                                      <el-switch v-model="memberActive" on-color="#13ce66" on-text="" off-text="" @change="memberActiveChange()">
                                      </el-switch>
                                  </div>
                                  -->
                </div>
                <el-select v-model="filterTaskState" placeholder="筛选任务" size="small" @change="filterTaskStateChange"
                           style="width:100px;margin:14px 0 14px 40px;float:left;">
                  <el-option
                    v-for="item in filterOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>

                <div class="block" id="datePicker" style="float:right;margin-top:13px;">
                  <el-date-picker v-model="showMonth" :clearable="false" :editable="false"
                                  v-show="(taskType=='today')||(taskType=='month')" @change="monthChange()" type="month"
                                  placeholder="选择月">
                  </el-date-picker>
                  <el-date-picker v-model="showWeek" :clearable="false" :editable="false" v-show="taskType=='week'"
                                  type="week" @change="weekChange" placeholder="选择周" format="yyyy 第 WW 周"
                                  :picker-options="pickerOptions2">
                  </el-date-picker>
                  <el-date-picker v-model="showYear" :clearable="false" :editable="false" v-show="taskType=='year'"
                                  @change="yearChange()" type="year" placeholder="选择年">
                  </el-date-picker>

                  <el-date-picker
                    v-model="showDateRange"
                    style="width:210px;font-size:13px;"
                    v-show="taskType == 'project'"
                    type="daterange"
                    size="large"
                    align="right"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :picker-options="pickerOptions3()">
                  </el-date-picker>

                </div>
              </div>
              <div class="filter-condition">
                <ul>
                  <li>所有网络</li>
                  <li>进行中</li>
                  <li>筛选</li>
                  <li>按截止日期排序</li>
                </ul>
              </div>

              <!-- 写右边的内容 -->

              <router-view ref="taskChildPage" @changeTodayShowType="changeTodayShowType" class="view" keep-alive
                           transition transition-mode="out-in">
              </router-view>
              <project-dialog ref="projectDialog"></project-dialog>
            </div>
          </div>
        </div>
      </div>
      <!--</template>-->
    </div>

  </div>

</template>
<div id="cli_dialog_div"></div>
<div id="cli_dialog_div"></div>
<div id="cli_dialog_div"></div>
<script>
  import swiper from 'swiper';
  import '../../../static/z39pc/js/jquery-2.1.0.js'
  import draggable from 'vuedraggable'
  import _ from "underscore";
  import moment from "moment";
  import projectDialog from '../../components/task/projectDialog.vue'
  import headerNav from '../../components/all/header.vue'
  import api from '../../api';
  import {taskAndTag} from "../../common/mixin";
  import {mixinPc} from "../../common/mixinPc";
  import {bus} from "../../common/bus";
  import XLSX from 'xlsx'
  import {
    mapState,
    mapActions
  } from 'vuex'

  var projectSwiper = function () {
    var swiper = new Swiper('.project-swiper', {
      slidesPerView: 'auto',
      spaceBetween: 0,
      freeMode: true,
      freeModeMomentumRatio: 0.5,
      freeModeMomentumBounce: false,
      freeModeMomentum: true,
      scrollbarHide: true
    });
    return swiper
  }
  var typeArr = ['today', 'week', 'month', 'year', 'project'];

  var initPage = function (me) {
    $('body').css({
      'height': '100%',
      'overflow': 'hidden'
    })
    $('#menu-show').click(function () {
      $(this).hide();
      $('.projectList').show();
      $('.memberList').hide();
      $('.type_filter.switch3Ul').css({
        'left': '300px'
      });
    })

//		$('.inUl.prolist').on('click', 'li', function() {
//			$(this).addClass('active').siblings().removeClass('active')
//		})
    //缩小收纳箱
    //快捷键关闭任务详情
    var showAddHideBox = function (action) {
      if (action == 'hide') {
        $('#mainContent .container-left-content').animate({
          width: '50px',
        }, 300, function () {
          $('.container-left-content .show-box').show();
        })
        $('#mainContent .container-right').animate({
          left: '50px',
        }, 300)
        $('.container-left-content').removeClass('active')
      } else if (action == 'show') {
        $('#mainContent .container-left-content').animate({
          width: '311px',
        }, 300, function () {
          $('.container-left-content .show-box').hide();
        })
        $('#mainContent .container-right').animate({
          left: '311px',
        }, 300)
        $('.container-left-content').addClass('active')
      }
    }
    $(window).on('keyup', function (e) {
      e.preventDefault()
      if (e.keyCode == 27) {//esc
        var index = $('#xx li.active').index()
        // $('.task-detail-container').animate({
        // 	right: '-400px'
        // }, 300)
        if (me.$route.name == '今日任务') {
          $('.kanban-main-warp .kanban-main-container').animate({
            right: '45px'
          }, 300)
        } else {
          $('.kanban-main-warp .kanban-main-container').animate({
            right: '-24px'
          }, 300)
        }
        if (me.$route.name == '单任务') {
          history.back();
        }
      } else if (e.keyCode == 16) {//shift
        return;
        if ($('.container-left-content').hasClass('active')) {
          showAddHideBox('hide')
        } else {
          showAddHideBox('show')
        }
      }
    })
    $('.container-left-content').on('click', '.storageBox .hide-box', function () {
      showAddHideBox('hide')
    })
    $('.container-left-content').on('click', '.show-box', function () {
      showAddHideBox('show')
    })
    //显示隐藏任务详情
    $('body').on('dblclick', '.kanban-item-warp ul.allow-detail-click li', function (e) {
      $('.task-detail-container').show()
      $('.task-detail-container').animate({
        right: '-24px'
      }, 300)
      $('.kanban-main-warp .kanban-main-container').animate({
        right: '340px'
      }, 300)
      e.cancelBublle = true;
      e.stopPropagation();
      $(this).addClass('active');
      $(this).siblings().removeClass('active');
      itemAni(this);
    })
    $('body').on('click', '.task-detail-container .close', function () {
      $('.task-detail-container').animate({
        right: '-400px'
      }, 300)
      $('.kanban-main-warp .kanban-main-container').animate({
        right: '70px'
      }, 300)
    })

    $('body').on('dragstart', '.dragArea li.kanban-Item-container', function (e) {
      if (me.$route.name == '项目任务' && !me.projectId) {
        return false;
      }
      $('.dragArea').css('border-color', '#000')
    })
    $('body').on('drop', '.dragArea', function (e) {
      $('.dragArea').css('border-color', 'transparent')
    })

    //点击任务的时候,动画效果
    $('body').on('click', '#tagTmpList li.kanban-Item-container .right', function (e) {
      e.cancelBublle = true;
      e.stopPropagation();
      var clickParant = $($(this).parents('.kanban-Item-container')[0]);
      $(clickParant).toggleClass('active');
      $(clickParant).siblings().removeClass('active');
      itemAni(clickParant);
//			$('.kanban-card-container').find('li.kanban-Item-container').removeClass('triangle-badge-rt');
//			$(clickParant).parent().children().each(function() {
//				if($(this).attr('data-quickNo') < 10) {
//					$(this).addClass('triangle-badge-rt');
//				}
//			})
//			$('.kanban-card-container').find('.header').removeClass('active')
//			$(clickParant).parents('.kanban-card-container').find('.header').addClass('active');

    })
    $('body').on('click', '.body-tr-container .kanban-item-warp', function () {
      if (!$(this).parents('.kanban-card-container').find('.header').hasClass('not-active')) {
        $(this).parents('.kanban-card-container').find('.header').click();
//				$('.kanban-card-container').find('.header').removeClass('active')
//				$(this).parents('.kanban-card-container').find('.header').addClass('active');

      }


    })

    //点击任务头
    $('body').on('click', '.kanban-card-container .header', function () {
      if (!$(this).hasClass('not-active')) {
        $('li.kanban-card-container .header').removeClass('active');
        $(this).addClass('active');

        $('.kanban-card-container').find('li.kanban-Item-container').removeClass('triangle-badge-rt');
        $(this).parents('.kanban-card-container').find('li.kanban-Item-container').each(function () {
          if ($(this).attr('data-quickNo') < 10) {
            $(this).addClass('triangle-badge-rt');
          }
        })
      }
    })

    function itemAni(item) {
      $(item).removeClass("animated bounceIn");
      setTimeout(function () {
        $(item).addClass("animated bounceIn");
      }, 10);
    }

    //列表头部添加任务
    $('body').on('click', '.head-tr .addItem', function () {
      if ($(this).hasClass('is-show-dialog')) {
        return;
      }
      if ($(this).hasClass('icon-close')) {
        $(this).prev().hide();
        $(this).removeClass('icon-close').addClass('icon-add_circle');
      } else {
        $('.kanban-card-container .head-tr .card-rename').hide();
        $('.kanban-card-container .head-tr .addItem').removeClass('icon-close').addClass('icon-add_circle');
        $(this).prev().show();
        $(this).addClass('icon-close').removeClass('icon-add_circle');
      }
    })
    $('body').on('click', '.kanban-card-container .no-task-container', function () {
      $(this).parent().parent().siblings('.head-tr').find('.addItem').click();
    })

  }

  export default {
    data() {
      return {
        filterTaskState: '',
        filterOptions: [{
          value: '0',
          label: '全部'
        }, {
          value: '1',
          label: '未完成'
        }, {
          value: '2',
          label: '已完成'
        },],
        boxTab: 'box',
        dateMonth: new Date(),
        memberActive: false,
        boxList: [],
        projectSwiper: '',
        projectList: [],
        memberList: [],
        todayList: [],
        todayTags: [],
        taskType: 'today',
        fullscreenLoading: true,
        addTaskTitle: '',
        addTaskTitlePlaceholder: '任务标题\n任务描述(回车换行后的内容自动添加到描述)快速添加快捷键Ctrl+Enter',
        addBtnLoading: false,
        dragItemData: '',
        showMonth: '',
        showYear: '',
        showWeek: new Date(),
        showDateRange: {},
        pickerOptions2: {
          firstDayOfWeek: 1
        },
        timeRange() {
          var nowDate = new Date();

          function calc(n) {
            var date = new Date();
            var t = date.getTime();
            var m = t - n * 24 * 3600 * 1000;
            var s = new Date(m);
            return s.getFullYear() + "-" + (s.getMonth() + 1) + "-" + s.getDate()
          }

          var initTime = new Date();
          initTime.setMonth(0); // 本年初始月份
          initTime.setDate(1); // 本年初始时间
          var differenceVal = nowDate - initTime; // 今天的时间减去本年开始时间，获得相差的时间
          var todayYear = Math.ceil(differenceVal / (24 * 60 * 60 * 1000)); // 获取今天是今年第几天
          var weekYear = Math.ceil(todayYear / 7); // 获取今天是今年第几周
          let cls = this.getDateRange();
          return {
            ['上月(' + (cls.monthRange(0).b.getMonth()) + '月)']: cls.monthRange(-1),
            ['本月(' + (cls.monthRange(1).b.getMonth()) + '月)']: cls.monthRange(0),
            ['下月(' + (cls.monthRange(2).b.getMonth()) + '月)']: cls.monthRange(1),
            ['上周(' + (weekYear - 1) + 'th)']: cls.weekRange(-1),
            ['本周(' + weekYear + 'th)']: cls.weekRange(0),
            ['下周(' + (weekYear + 1) + 'th)']: cls.weekRange(1),
            [calc(7)]: {b: new Date(calc(7)), e: new Date(calc(7))},
            [calc(6)]: {b: new Date(calc(6)), e: new Date(calc(6))},
            [calc(5)]: {b: new Date(calc(5)), e: new Date(calc(5))},
            [calc(4)]: {b: new Date(calc(4)), e: new Date(calc(4))},
            [calc(3)]: {b: new Date(calc(3)), e: new Date(calc(3))},
            [calc(2)]: {b: new Date(calc(2)), e: new Date(calc(2))},
            [calc(1)]: {b: new Date(calc(1)), e: new Date(calc(1))},
            [calc(0)]: {b: new Date(calc(0)), e: new Date(calc(0))},
            [calc(-1)]: {b: new Date(calc(-1)), e: new Date(calc(-1))},
            '近一年': cls.yearRange(0),
            '全部': {b: '', e: ''}
          };

        },
        pickerOptions3() {
          let _this = this;
          let shortcuts = {shortcuts: []};
          let range = this.timeRange();
          Object.keys(range).forEach(key => {
            shortcuts['shortcuts'].push({
              text: key,
              onClick(picker) {
                const end = range[key].e; //end是js的Date对象.
                const start = range[key].b;
                var due = end ? moment(end).format("YYYY-MM-DD") : "";
                _this.$store.commit("z39pc/setValue", {projectDue: due});
                // console.warn("project pick",_this.projectDue);
                picker.$emit('pick', [start, end]);
              }
            });
          });
          return shortcuts;
        },
        format: function (value, name) {
          return `${value[0]}:${value[1]}`
        },
        showTimeNeed: false,
        showPopupPicker: false,
        showSummary: false,
        taskCurr: {
          title: ""
        },
        taskDoing: null,
        sortStr: "",
        todayArr: [],
        todaySort: [],
        todaySortArr: [],
        visibility: false,
        daySelect: "",
        stateAdd: false,
        taskTitle: "",
        taskDesc: "",
        nonesList: [], //收纳箱列表,
        projectId: '', //选中的项目
      };
    },
    sockets: {  //事件监听
      connect: function () {
        if (this.$socket.id == null) return;
        this.$store.commit("sid", {sid: this.$socket.id});
        console.log("sockets connect in", this.$socket.id);

        setTimeout(() => {
          if (!this.wsLogin && this.uid && api.token) this.$socket.emit('wsLogin', JSON.stringify({
            uid: this.uid,
            token: api.token
          }));
        }, 200)
      },
      error: function (e) {
        // console.log("socket error",e);
      },
      taskNumUpdate: function (val) {
        if (!this.socketOpen) return;
        let data = JSON.parse(val);
        let curr = data.curr;
        let total = data.total;
        const h = this.$createElement; //`任务数:${curr}/${total}`
        this.$message({
          title: '进度',
          message: `任务数:${curr}/${total}`,
          type: 'info'
        });
        // console.log("taskNumUpdate",data);
      },
      tasklistUpdate: function (val) {
        if (!this.socketOpen) return;
        let task, tasks;
        try {
          task = JSON.parse(val);
          tasks = task instanceof Array ? task : [task];
          this.$store.commit({type: "z39/taskToDB", tasks: tasks, act: "add"});

          console.log('server tasklistUpdate:', tasks.length);
        } catch (e) {
          // console.log("error:",e) ;
        }
        // console.log('server tasklistUpdate:');
        // console.log('server tasklistUpdate:',val);
      },
      taskUpdate: function (val) {
        if (!this.socketOpen) return;
        let task, tasks;
        try {
          task = JSON.parse(val);
          tasks = task instanceof Array ? task : [task];
          this.$store.commit({type: "z39/taskToDB", tasks: tasks, act: "add"});

          console.log('server taskUpdate:', tasks.length);
        } catch (e) {
          // console.log("error:",e) ;
        }
        // console.log('server taskUpdate:');
        // console.log('server taskUpdate:',val);
      },
      tagUpdate: function (val) {
        if (!this.socketOpen) return;
        try {
          let tag = JSON.parse(val);
          this.$store.commit({type: "z39/tagUpdate", tag: tag});
          bus.$emit('tagUpdate');
          console.log('server tagUpdate:', tag);
        } catch (e) {
        }
      },
      wsloginResult: function (val) {
        let data = JSON.parse(val);
        if (data.errno > 0) this.$store.commit("wsLogin", {wsLogin: true});
        console.log('wslogin登录结果:', data);
      },
      taskWarn: function (val) {  //任务超时提醒,任务开始提醒.
        let data = JSON.parse(val);
        let msg = {title: '任务提示', message: '', type: "info", duration: 3000};
        msg = Object.assign(msg, data);
        this.$notify(msg);
        // console.log("task:",data);
      },
    clock:function(val){
      let data = JSON.parse(val) ;
      let time = data.phase == 1 ? 10:0 ;
      this.$notify({
        title:"闹钟",
        message: "任务:"+(data.title || "时间清单"),
        position: 'bottom-left',
        type: 'warning',
        duration: 15000
      })
      console.log("clock",data);
    },
      msgSys: function (val) {
        console.log('系统消息:', val);
      }
    },
    components: {
      draggable,
      'project-dialog': projectDialog,
      'header-nav': headerNav
    },
    mixins: [taskAndTag, mixinPc],
    computed: {
      nones: function () {
        var _this = this;
        var list = this.taskAll.filter(t => {
          return t.uid == _this.uid && (!t.state || t.state == 'started') && !t.parid && !t.pid && (!t.tags || !t.tags["due"])
        });
        this.nonesList = Object.assign([], list);
        console.log("nones", this.nonesList.length);
      },
      getShowMonth: function () {
        return this.$store.state.z39.showMonth;
      },
      getShowYear: function () {
        return this.$store.state.z39.showYear;
      },
      ...mapState({
        uid: state => state.vux.uid,
        sid: state => state.vux.sid,  //websocket id
        socketOpen: state => state.vux.socketOpen,  //socket打开状态.
        wsLogin: state => state.vux.wsLogin,
        minDate: state => state.z39.minDate,
        maxDate: state => state.z39.maxDate,
        taskAll: state => state.z39.taskAll,
        tagDic: state => state.z39.tagDic,
        taskDic: state => state.z39.taskDic,
        tagitems: state => state.z39.tagitems,
        tagitemDic: state => state.z39.tagitemDic,
        days: state => state.z39.days,
        projects: state => state.z39.projects,
        members: state => state.z39.members,
        filterState: state => state.z39.filterTaskState,
        projectDue: state => state.z39pc.projectDue,
      })
    },
    watch: {
      "taskAll": {
        handler() {
          this.nones;
        },
        deep: true,
      },
      "$route": function (to, from) {
        if (this.$route.path == '/' || this.$route.path == '/m_index') {
          console.log("index page in!");

        } else if (this.$route.name.indexOf('项目任务') >= 0) {

        }
        //路由发生变化时，更新标签模板的顺序，否则会出问题,放在today下面会监听不到
        this.$store.commit({
          type: "z39/tagTmpResort"
        });
      },
      "uid": function () {
        if (this.uid) {
          this.monthChange()
        }
        this.showInviteDialog()
      },
      "tagitems": function () {
        var temp = [];
        var len = this.tagitems.length;
        for (var i = 0; i <= len - 1; i++) {
          var item = this.tagitems[i];
          temp.push({
            key: item.key,
            name: item.name
          });
        }
        this.flagAllArr = temp;
        // this.$nextTick(() => {
        //   this.$refs.scrollerEvent.reset({top: 0})
        // })
      },
      "showAddTag": function () {
        let temp = [],
          tempArr = [];
        if (!this.showAddTag) { //关闭窗口
          var len = this.flagUse.length;
          for (var i = 0; i <= len - 1; i++) {
            var item = this.flagUse[i];
            temp.push(item.key);
          }
          let news = _.difference(temp, this.tagsOld);
          let dels = _.difference(this.tagsOld, temp);
          this.tagsAdd(news, false, this.taskCurr);
          this.tagsDel(dels, false, this.taskCurr);
        } else { //打开窗口,保存临时值,做后期比对.
          var tags = this.taskCurr.tags;
          for (var key in tags) {
            temp.push({
              key: key,
              name: this.tagitemDic[key]
            });
            tempArr.push(key);
          }
          this.flagUse = temp;
          this.tagsOld = tempArr;
        }
      },
      "daysDic": function () {
        this.days = this.daysDic[this.showMonth] || [];
      },
      'getShowMonth': function () {
        this.showMonth = this.$store.state.z39.showMonth;
        this.showYear = this.$store.state.z39.showYear;
      },
      'getShowYear': function () {
        this.showMonth = this.$store.state.z39.showMonth;
        this.showYear = this.$store.state.z39.showYear;
      },
      'socketOpen': function () {
        if (!this.socketOpen) {
          this.$socket.close();
        } else {
          if (!this.sid) this.$socket.open();
        }
      },
      projects: function () {
        console.log(this.projectSwiper)
        this.projectSwiper.setWrapperTranslate(0)
        setTimeout(() => {
          this.projectSwiper.updateSlidesSize()
        }, 500)
      }
    },
    created() {
      this.showMonth = this.$store.state.z39.showMonth;
      this.showYear = this.$store.state.z39.showYear;

      let dataClass = this.getDateRange();
      let currentMonth = dataClass.monthRange(0);
      let end = currentMonth.e; //时间筛选,给拖动到项目的任务添加due
      var due = end ? moment(end).format("YYYY-MM-DD") : "";
      this.$store.commit("z39pc/setValue", {projectDue: due});
      this.showDateRange = [currentMonth.b, currentMonth.e];

      if (this.$route.name == '单任务') {
        this.$router.go(-1)
      }
      this.daySelect = moment().format("YYYY-MM-DD");

    },
    filters: {
      dayMin: function (month) {
        return month.replace("-", "")
      },
      dayOnly: function (day) {
        var dayMon = moment(day);
        var value = dayMon.day();
        var todayStr = moment().format("YYYY-MM-DD");
        var dayDic = {
          1: "一",
          2: "二",
          3: "三",
          4: "四",
          5: "五",
          6: "六",
          0: "日"
        };
        var show = "";
        if (day == todayStr) {
          show = "今";
        } else {
          show = (value == 0 || value == 6) ? dayDic[value] : dayMon.date();
        }
        return show;
      }
    },
    watch: {
      showDateRange: 'daterangeChange'
    },
    methods: {
      dragStart: function () {
        $("body").addClass('draging');
      },
      dragEnd: function () {
        $("body").removeClass('draging');
      },
      cleanEvent(e) {
        e.stopPropagation();
        e.preventDefault();
      },
      dropHandle(e) {
        e.stopPropagation();
        e.preventDefault();
        console.log(e)
        console.log(e.dataTransfer)


        var dt = e.dataTransfer;
        var files = dt.files;
        //判断后缀名是否为excel格式，如果是进入读取excel。
        if(files[0].name.lastIndexOf("xls")>-1 || files[0].name.lastIndexOf("xlsx")>-1)
        {
          this.readExcel(files[0])
        }
        else
        {
          this.readFile("filelist", files);
        }

      },
      /*
       * 功能: 读取excel文件后与projects比较项目名称获取项目id，然后对excel文件项目进行分组，并向后端发送数据
       * 参数: file为文件信息。
       * datetime: 2018-09-05
       * 作者：direction
       */
      readExcel(file) {
        let vm = this;
        var handleResult = function (file) {
          var reader = new FileReader();
          reader.onload = function (e) {
            try {
              const data = e.target.result;
              const workbook = XLSX.read(data, {
                type: 'binary'
              });
             // console.log(vm.projects);
              //默认一组是unproject
              var prolist = [{type: "unproject", id: 0, tasks: []}];
              for (let sheet in workbook.Sheets) {
                const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
               // console.log(sheetArray)

                for(let key in sheetArray)
                {
                  var obj = {};
                  var flag = -999;
                  console.log(sheetArray[key]['项目名称'])
                  if(!!sheetArray[key]['项目名称']  && sheetArray[key]['项目名称'] != '')
                  {
                    var tmp = _.findWhere(vm.projects, { title:sheetArray[key]['项目名称'] })
                    if(tmp != undefined)
                    {
                      flag = tmp.id;
                      prolist.push({type: "project", id: tmp.id, tasks: []})
                    }
                  }
                  if(!!sheetArray[key]['任务标题']  && sheetArray[key]['任务标题'] != '')
                  {
                    obj.title = sheetArray[key]['任务标题']
                  }
                  if(!!sheetArray[key]['任务描述']  && sheetArray[key]['任务描述'] != '')
                  {
                    obj.desc = sheetArray[key]['任务描述']
                  }
                  if( !!sheetArray[key]['日期']  &&sheetArray[key]['日期'] != '')
                  {
                    var dueobj = {}
                    dueobj.due = moment(sheetArray[key]['日期']).format("YYYY-MM-DD")
                   // console.log(dueobj.due)
                    obj.tags=dueobj
                  }
                  if(flag == -999)
                  {
                    prolist[0].tasks.push(obj)
                  }
                  else
                  {
                    var prolistIndexOf = _.findWhere(prolist,{id:flag})
                    if(prolistIndexOf != undefined)
                    {
                      var sindex = _.indexOf(prolist,prolistIndexOf)
                      prolist[sindex].tasks.push(obj);
                    }
                  }
                }

              }
             // console.log(prolist);
              //console.log(JSON.stringify(prolist));

              api.importExcel({
                prolist : prolist
              }).then(data => {
                //console.log(data);
                vm.$message({type: 'info', message: data.data});
              })
            } catch (e) {
              console.log(e)
              vm.$message.warning('文件类型不正确！');
              return false;
            }
          };
          reader.readAsBinaryString(file);
        };
          handleResult(file)


      },
      readFile(type, data) {
        let vm = this;
        var handleResult = function (file) {
          var reader = new FileReader();
          reader.onload = function (e) {
            api.importTask({
              content: e.target.result
            }).then(data => {
              console.log(data);
              vm.$message({type: 'info', message: data.data});
            })
          };
          reader.readAsText(file);
        };
        for (var i = 0; i < data.length; i++) {
          handleResult(data[i])
        }
      },

      changeTodayShowType(type) {
        if (+type === 2 && this.taskType === 'project') {
          let date = new Date()
          this.showDateRange = [date, date]
        } else if (+type !== 2 && this.taskType === 'project') {
          let currentMonth = this.getDateRange().monthRange(0);
          this.showDateRange = [currentMonth.b, currentMonth.e];
        }
      },
      getDateRange() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay(); //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();

        //获得某月的天数
        var getMonthDays = function (myMonth) {
          var monthStartDate = new Date(nowYear, myMonth, 1);
          var monthEndDate = new Date(nowYear, myMonth + 1, 1);
          var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
          return days;
        }
        //获得年区间
        var yearRange = function (year) {
          var stime = new Date();
          var etime = new Date(nowYear + year, nowMonth, nowDay);
          return {b: stime, e: etime};
        }
        //获得月区间
        var monthRange = function (month) {
          var stime = new Date(nowYear, nowMonth + month, 1);
          var etime = new Date(nowYear, nowMonth + month, getMonthDays(nowMonth + month));
          return {b: stime, e: etime};
        }
        //获得周区间
        var weekRange = function (week = 0) {
          var stime = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + week * 7 + 1);
          var etime = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + week * 7 + 7);
          return {b: stime, e: etime};
        };

        return {
          getMonthDays: getMonthDays,
          yearRange: yearRange,
          monthRange: monthRange,
          weekRange: weekRange
        };
      },
      onChangeTime(index) {
        this.taskType = typeArr[index];
        $('#listTypeTab li:eq(' + index + ')').addClass('active').siblings().removeClass('active');
        $('.activeCircle.center').css({left: index * 40 + 'px'});
      },
      //收纳箱添加任务
      addTask: function () {
        if (!this.addTaskTitle.split('\n')[0]) {
          this.$message({
            message: '请输入任务标题',
            type: 'warning'
          });
          return;
        }
        var importReg = /```tlog\n([\s\S]*)```/g;
        var matchObj = this.addTaskTitle.match(importReg);

        var str;
        var prolist;
        if (matchObj != null) {  //str.length >0
          str = this.addTaskTitle.replace(importReg, "$1");
          prolist = parseTlog(str);  //parseTlog.js
          if (prolist.length == 0 || prolist[0].tasks.length == 0) return this.$message({
            message: '缺少导入数据',
            type: 'warning'
          });
          this.addBtnLoading = true;
          this.tasksAdd({tasks: prolist[0].tasks}).then(data => {
            this.addTaskTitle = ''
            this.addBtnLoading = false;
          }, data => {
            this.addBtnLoading = false;
          });
          console.log(prolist, str);
          return;
        }
        this.addBtnLoading = true;
        var params = {
          uid: 1,
          title: this.addTaskTitle.split('\n')[0],
          desc: this.addTaskTitle.split('\n')[1] || ''
        }
        this.taskAdd(params).then(data => {
          this.addTaskTitle = ''
          this.addBtnLoading = false;
        }, data => {
          this.addBtnLoading = false;
        });
      },
      dragAddNones: function (event) {
        var routeName = this.$route.name;
        var taskId = $(event.clone).attr("taskId");
        var taskItem = this.taskDic[taskId];
        var tagId1 = this.tagDic[taskId + '_due'] ? this.tagDic[taskId + '_due'].id : '';
        if (tagId1) {
          this.tagDel({id: tagId1, key: 'due'}, true, taskItem);
        }
        if (this.projectId) {
          var tagId2 = this.tagDic[taskId + '_' + $(event.from).attr('tagKey')].id;
          //this.tagDel({id: tagId2,key: $(event.from).attr('tagKey')}, true, taskItem);
          this.taskSet({pid: '', id: taskItem.id, state: ''}, taskItem); //添加pid
        }

      },
      dragRemove: function (event) {

        //				return false;
      },
      dragMove: function (event) {
        var routeName = this.$route.name;
        if (routeName == '项目任务' && !this.projectId) {
          return false;
        }
        //			this.dragItemData = event.relatedContext.element;
        //			console.log(this.nones.length)
      },
      sortdataAdd(sdata) {
        let _this = this;
        api.sortdayAdd(sdata).then(data => {
          if (data && data.errno == 0 && data.data > 0) {
            data = data.data;

            //console.log(data);
          } else { //发生错误.
            _this.$message({
              message: data.errmsg,
              type: 'error'
            });
          }
        })
      },

      onEdit(item, index) {
        this.taskCurr = item;

        let type = this.editType;
        //console.log("need", this.showTimeNeed, _.clone(item).tags.due, _.clone(item));
        switch (type) {
          case 0:
            this.showEditBtn = true;
            this.asBtnCurr = planBtnArr;
            break;
          case 1:
            let taskneed = item.tags["need"];
            this.timeNeed = (taskneed && taskneed.indexOf(":") > -1) ? taskneed.split(":") : this.timeNeed;
            this.showTimeNeed = true;
            break;
          case 2:
            this.showEditBtn = true;
            let arr = [];
            arr.push(taskBtnItem);
            if (item.state == "" || item.state == "due" || item.state == "need") {
              arr.push(startBtnItem);
            } else if (item.state == "started") {
              arr.push(toggleBtnItem);
            } else if (item.state == "toggle") {
              arr.push(restartBtnItem);
            }
            if (item.state == "done") {
              arr.push(noneBtnItem);
            } else {
              arr.push(doneBtnItem);
            }

            this.asBtnCurr = arr;
            break;
          case 3:
            this.resetSummary();
            this.showSummary = true;
            break;
          case 4:
            //在tabitemclick 中.
            this.showAddTag = true;
            break;
          default: //从添加状态点击任务,直接进入查看模式.

            console.error("index:", index);
            break;
        }
      },
      changeTime() {
        this.visibility = true;
      },
      monthChange() {
        var monthVal = moment(this.showMonth).format("YYYY-MM");
        this.$store.commit({
          type: "z39/changeDate",
          value: monthVal,
          dateType: 'month'
        });
        //			var day=this.$store.state.z39.selectedDayDate.split('-')[2];
        //			this.$store.commit({ type: "z39/changeDayDate", day:day });
        this.daysGet({
          type: 1,
          month: monthVal
        });
      },
      daterangeChange() {
        console.log('date range change', this.projectId)
        this.$refs.taskChildPage.daterangeChange(this.showDateRange);
      },
      weekChange(val) {
        var weekVal = val;
        this.$store.commit({
          type: "z39/changeDate",
          value: weekVal,
          dateType: 'week'
        });
      },
      yearChange() {
        var yearVal = moment(this.showYear).format('YYYY');
        this.$store.commit({
          type: "z39/changeDate",
          value: yearVal,
          dateType: 'year'
        });
      },
      onDay(day) {
        this.daySelect = day;
        this.sortdayGet(day).then(data => {
          this.sortStr = data.sorts;
        });
      },
      clickAdd() {
        this.stateAdd = true;
        this.resetInput();
      },
      resetInput() {
        this.addTaskTitle = "";
        this.taskTitle = "";
        this.taskDesc = "";
      },
      saveSort() {
        var ids = [];
        var len = this.todayArr.length;
        for (var i = 0; i <= len - 1; i++) {
          var item = this.todayArr[i];
          ids.push(item.id);
        }
        this.sortdataAdd({
          day: this.daySelect,
          sorts: ids.join(",")
        });
      },
      projectCli: function (pid) {
        this.onChangeTime(4);
        this.projectId = pid;

        let url_ext = '';
        if (pid) url_ext += '/' + pid;

        var _this = this;
        var routeName = this.$route.name;
        this.$router.push({
          path: '/projectTask' + url_ext,
        })
        if (routeName == '项目任务') {
          var proTime1 = setTimeout(function () {
            clearTimeout(proTime1)
            _this.$refs.taskChildPage.getTagTmpDev(pid, _this.memberActive)
          }, 1000)
        } else {
          var proTime1 = setTimeout(function () {
            clearTimeout(proTime1)
            _this.$refs.taskChildPage.getTagTmpDev(pid, _this.memberActive)
          }, 1000)
        }

//				}
      },
      memberActiveChange: function () {
        var routeName = this.$route.name;
        if (this.projectId && routeName == '项目任务') {
          this.$refs.taskChildPage.getTagTmpDev(this.projectId, this.memberActive)
        }
      },
      showProjectDialog: function (type) {
        if (type == 'edit') {
          this.$refs.projectDialog.editDialog(this.projectId);
        } else if (type == 'add') {
          this.$refs.projectDialog.showDialog({});
        }

      },
      deleteProject: function () {
        var _this = this;
        if (!this.projectId) {
          this.$message({
            message: '请先选择项目',
            type: 'warning'
          });
        } else {
          this.$confirm('是否确认删除当前项目?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            _this.projectDel(_this.projectId);
            _this.projectCli('')
//			          _this.$refs.taskChildPage.getList('', _this.memberActive)
          }).catch(() => {

          });
        }
      },
      showInviteDialog: function () {
        var url = location.href.split('?')[1];
        if (!(this.uid && url && url.indexOf('action=invite') > -1)) {
          return
        }
        var urlParams = url.replace(/^#+$/, '').replace('?', '').split('&');

        var pid = urlParams[1].split('=')[1];
        var pwd = urlParams[3].split('=')[1];
        var type = urlParams[2].split('=')[1];
        api.getInviteTitle({xid: pid, type: type}).then(data => {
          if (data.errno != 0) {
            this.showNotice(data.errmsg, 'warning');
            return;
          }
          this.$confirm('是否确认加入' + data.data + '项目?', '邀请', {
            confirmButtonText: '加入',
            cancelButtonText: '拒绝',
            type: 'info'
          }).then(() => {
            api.invitefriends({type: type, xid: pid, pwd: pwd}).then(data => {
              history.replaceState({}, '时间管理', location.href.replace('action=invite&', ''))

              if (data && data.errno == 0) {
                this.$message({
                  type: 'success',
                  message: '加入成功'
                });
              } else { //发生错误.
                this.$message({
                  message: data.errmsg,
                  type: 'error'
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已拒绝'
            });
          });
        })
      },
      filterTaskStateChange: function (value) {
        this.$store.commit({
          type: "z39/setFilterState",
          state: value
        });
      }
    },
    mounted: function () {
      this.nones;
      this.filterTaskState = this.filterState;
      var _this = this;
      if (this.uid) this.monthChange()
      initPage(_this);
      if (this.$route.path == '/') {
        this.$router.push('/todayTask')
      }
      var path = this.$route.path;
      var index = 0;
      typeArr.some((type, i) => {
        index = i;
        return path.indexOf(type) != -1;
      })
      this.onChangeTime(index);
      this.showInviteDialog();
      this.projectSwiper = projectSwiper()

      var pid = this.$route.params.pid;
      if (pid) this.projectId = pid;

      // this.$socket.emit('connect', "7dtime.com");
    },
    events: {
      "changeTodayShowType": function () {

      }
    }
  }
</script>
<style>
  .task-main-container .storageBox #buttonDiv .el-button:after {
    content: '';
    position: absolute;
    width: 100%;
    height: 0;
    left: 0;
    top: 15px;
    background: #00529a;
    box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.15);
  }

  .task-main-container .storageBox #storageUlDiv {
    top: 192px;
    bottom: 0;
  }

  body.draging > div.el-popover {
    display: none !important;
  }
</style>
